package ui;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import model.AttributeDefinition;
import model.Customer;
import service.AttributeService;
import service.CustomerService;

public class AddCustomerPage {
    private Stage stage;
    private CustomerService customerService;
    private List<AttributeDefinition> attributes;
    
    // 存储动态创建的输入控件和选中的属性值
    private TextField nameField;
    private Map<Integer, TextField> attributeFieldMap = new HashMap<>();
    private Map<Integer, CheckBox> attributeHighlightMap = new HashMap<>();
    private Map<Integer, CheckBox> attributeInclusionMap = new HashMap<>();
    private Map<Integer, String> selectedAttributes = new HashMap<>();
    private Map<Integer, Boolean> highlightMap = new HashMap<>();

    public AddCustomerPage(Stage stage) {
        this.stage = stage;
        this.customerService = new CustomerService();
        this.attributes = AttributeService.getAllAttributes();
    }

    public void show() {
        VBox root = new VBox(40);  // 减少间距
        root.setPadding(new Insets(40));  // 减少内边距
        root.setAlignment(Pos.CENTER);
        root.setStyle("-fx-background-color: white;");

        // 标题
        Label titleLabel = new Label("添加客户信息");
        titleLabel.setStyle("-fx-font-size: 28px; -fx-font-weight: bold;");  // 减小标题字体

        // 表单
        GridPane form = new GridPane();
        form.setHgap(15);  // 减少水平间距
        form.setVgap(20);  // 减少垂直间距
        form.setAlignment(Pos.CENTER);
        form.setPadding(new Insets(30));
        form.setStyle("-fx-background-color: #f8f9fa; -fx-background-radius: 15;");

        // 客户名称（固定字段）
        Label nameLabel = new Label("客户名称:");
        nameField = new TextField();
        setupField(nameLabel, nameField);

        form.add(nameLabel, 0, 0);
        form.add(nameField, 1, 0);

        // 动态添加属性字段
        for (int i = 0; i < attributes.size(); i++) {
            AttributeDefinition attr = attributes.get(i);
            int attrId = attr.getAttributeId();
            
            Label attrLabel = new Label(attr.getDisplayName() + ":");
            TextField attrField = new TextField();
            CheckBox attrHighlight = new CheckBox("标红");
            CheckBox attrInclusion = new CheckBox("记录");
            
            // 默认选中"记录"复选框
            attrInclusion.setSelected(true);
            
            // 设置默认值
            if (attr.getDefaultValue() != null && !attr.getDefaultValue().isEmpty()) {
                attrField.setText(attr.getDefaultValue());
                selectedAttributes.put(attrId, attr.getDefaultValue());
            } else {
                selectedAttributes.put(attrId, "");
            }
            
            setupField(attrLabel, attrField);
            
            HBox attrBox = new HBox(8); // 减少水平间距
            attrBox.setAlignment(Pos.CENTER_LEFT);
            attrBox.getChildren().addAll(attrField, attrHighlight, attrInclusion);
            
            form.add(attrLabel, 0, i + 1);
            form.add(attrBox, 1, i + 1);
            
            // 存储控件到映射中
            attributeFieldMap.put(attrId, attrField);
            attributeHighlightMap.put(attrId, attrHighlight);
            attributeInclusionMap.put(attrId, attrInclusion);
            
            // 设置字段内容变化监听
            attrField.textProperty().addListener((observable, oldValue, newValue) -> {
                if (attrInclusion.isSelected()) {
                    selectedAttributes.put(attrId, newValue.trim());
                }
            });
            
            // 设置高亮复选框事件
            final int finalAttrId = attrId;
            attrHighlight.setOnAction(e -> {
                boolean isHighlighted = attrHighlight.isSelected();
                highlightMap.put(finalAttrId, isHighlighted);
                applyHighlight(attrField, isHighlighted);
            });
            
            // 设置记录复选框事件
            attrInclusion.setOnAction(e -> {
                boolean selected = attrInclusion.isSelected();
                attrField.setDisable(!selected);
                attrHighlight.setDisable(!selected);
                
                if (selected) {
                    // 添加到选中的属性中
                    selectedAttributes.put(attrId, attrField.getText().trim());
                } else {
                    // 从选中的属性中移除
                    selectedAttributes.remove(attrId);
                    attrHighlight.setSelected(false);
                    highlightMap.remove(attrId);
                    applyHighlight(attrField, false);
                }
            });
        }
        
        // 添加表单到滚动面板，以便处理字段过多的情况
        ScrollPane scrollPane = new ScrollPane(form);
        scrollPane.setFitToWidth(true);
        scrollPane.setFitToHeight(true);
        scrollPane.setStyle("-fx-background-color: transparent;");

        // 按钮容器
        HBox buttonBox = new HBox(20);  // 减少按钮间距
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.setPadding(new Insets(20, 0, 0, 0));

        // 保存按钮
        Button saveButton = new Button("保存");
        setupButton(saveButton, "button");
        saveButton.setOnAction(e -> saveCustomer());
        
        // 全部标红按钮
        Button allHighlightButton = new Button("全部标红");
        setupButton(allHighlightButton, "button");
        allHighlightButton.setOnAction(e -> toggleAllHighlights(true));
        
        // 全部取消标红按钮
        Button clearHighlightButton = new Button("取消标红");
        setupButton(clearHighlightButton, "button");
        clearHighlightButton.setOnAction(e -> toggleAllHighlights(false));
        
        // 一键全选按钮
        Button selectAllButton = new Button("全部记录");
        setupButton(selectAllButton, "button");
        selectAllButton.setOnAction(e -> toggleAllInclusions(true));
        
        // 一键取消全选按钮
        Button deselectAllButton = new Button("全部忽略");
        setupButton(deselectAllButton, "button");
        deselectAllButton.setOnAction(e -> toggleAllInclusions(false));

        // 返回按钮
        Button backButton = new Button("返回");
        setupButton(backButton, "back-button");
        backButton.setOnAction(e -> goBack());

        buttonBox.getChildren().addAll(saveButton, allHighlightButton, clearHighlightButton, selectAllButton, deselectAllButton, backButton);

        root.getChildren().addAll(titleLabel, scrollPane, buttonBox);

        Scene scene = new Scene(root, 1300, 1000);
        scene.getStylesheets().add(getClass().getResource("/css/logisticsList.css").toExternalForm());
        
        stage.setScene(scene);
        stage.setTitle("添加客户信息");
        stage.show();
    }
    
    private void toggleAllHighlights(boolean highlight) {
        // 遍历所有属性字段，设置高亮状态
        for (Map.Entry<Integer, CheckBox> entry : attributeHighlightMap.entrySet()) {
            CheckBox highlightBox = entry.getValue();
            if (!highlightBox.isDisabled()) {
                highlightBox.setSelected(highlight);
                applyHighlight(attributeFieldMap.get(entry.getKey()), highlight);
                highlightMap.put(entry.getKey(), highlight);
            }
        }
    }
    
    private void toggleAllInclusions(boolean selected) {
        for (AttributeDefinition attr : attributes) {
            int attrId = attr.getAttributeId();
            CheckBox inclusion = attributeInclusionMap.get(attrId);
            TextField field = attributeFieldMap.get(attrId);
            CheckBox highlight = attributeHighlightMap.get(attrId);
            
            inclusion.setSelected(selected);
            field.setDisable(!selected);
            highlight.setDisable(!selected);
            
            if (selected) {
                selectedAttributes.put(attrId, field.getText().trim());
            } else {
                selectedAttributes.remove(attrId);
                highlight.setSelected(false);
                applyHighlight(field, false);
                highlightMap.remove(attrId);
            }
        }
    }
    
    private void applyHighlight(TextField field, boolean highlight) {
        if (highlight) {
            field.setStyle("-fx-font-size: 14px; -fx-text-fill: red;");
        } else {
            field.setStyle("-fx-font-size: 14px;");
        }
    }
    
    private void saveCustomer() {
        // 验证客户名称不能为空
        String customerName = nameField.getText().trim();
        if (customerName.isEmpty()) {
            showAlert(Alert.AlertType.ERROR, "错误", "客户名称不能为空");
            return;
        }

        // 创建客户对象
        Customer customer = new Customer();
        customer.setCustomerName(customerName);

        // 设置选中的属性值和高亮状态
        for (Map.Entry<Integer, String> entry : selectedAttributes.entrySet()) {
            int attributeId = entry.getKey();
            String value = entry.getValue();
            
            // 设置属性值
            customer.setAttributeValue(attributeId, value);
            
            // 设置高亮状态
            boolean isHighlighted = highlightMap.containsKey(attributeId) && highlightMap.get(attributeId);
            customer.setAttributeHighlight(attributeId, isHighlighted);
        }

        // 保存客户信息
        int customerId = customerService.addCustomer(customer);
        if (customerId > 0) {
            showAlert(Alert.AlertType.INFORMATION, "成功", "客户信息已成功保存");
            clearFields();
        } else {
            showAlert(Alert.AlertType.ERROR, "错误", "保存客户信息失败");
        }
    }
    
    private void clearFields() {
        // 清空客户名称字段
        nameField.clear();
        
        // 清空所有属性字段
        for (Map.Entry<Integer, TextField> entry : attributeFieldMap.entrySet()) {
            int attributeId = entry.getKey();
            TextField field = entry.getValue();
            CheckBox highlight = attributeHighlightMap.get(attributeId);
            CheckBox inclusion = attributeInclusionMap.get(attributeId);
            
            // 重置字段值
            field.clear();
            if (attributes != null) {
                for (AttributeDefinition attr : attributes) {
                    if (attr.getAttributeId() == attributeId && attr.getDefaultValue() != null) {
                        field.setText(attr.getDefaultValue());
                        break;
                    }
                }
            }
            
            // 重置高亮状态
            highlight.setSelected(false);
            applyHighlight(field, false);
            
            // 重置记录状态
            inclusion.setSelected(true);
            field.setDisable(false);
            highlight.setDisable(false);
        }
        
        // 清空选中的属性和高亮状态
        selectedAttributes.clear();
        highlightMap.clear();
        
        // 重新添加默认值到选中的属性中
        if (attributes != null) {
            for (AttributeDefinition attr : attributes) {
                int attrId = attr.getAttributeId();
                if (attr.getDefaultValue() != null && !attr.getDefaultValue().isEmpty()) {
                    selectedAttributes.put(attrId, attr.getDefaultValue());
                } else {
                    selectedAttributes.put(attrId, "");
                }
            }
        }
    }
    
    private void goBack() {
        // 返回菜单页面
        try {
            CustomerListPage logisticsListPage = new CustomerListPage();
            logisticsListPage.start(new Stage());
            stage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupField(Label label, TextField field) {
        // 设置标签样式
        label.setStyle("-fx-font-size: 14px;");  // 减小标签字体
        
        // 设置输入框样式
        field.setPrefWidth(300);  // 减小输入框宽度
        field.setPrefHeight(30);  // 减小输入框高度
        field.setStyle("-fx-font-size: 14px;");  // 减小输入框字体
    }

    private void setupButton(Button button, String styleClass) {
        button.getStyleClass().add(styleClass);
        button.setStyle("-fx-font-size: 14px; -fx-padding: 8 20;");  // 减小按钮字体和内边距
        button.setPrefWidth(120);  // 减小按钮宽度
        button.setPrefHeight(35);  // 减小按钮高度
    }
    
    private void showAlert(Alert.AlertType alertType, String title, String content) {
        Alert alert = new Alert(alertType);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
} 